package com.minelx.sqlstructures.core.database;

import com.alibaba.fastjson.JSONObject;
import com.minelx.sqlstructures.core.table.ITable;
import com.minelx.sqlstructures.core.table.JsonTable;
import com.minelx.sqlstructures.core.values.FieldValues;

import java.util.List;

import static java.util.stream.Collectors.toList;

// FIXME 2021/7/1  replace with: Factory
public class JsonDatabase implements IDatabase {
	private final JSONObject jsonData;

	private final List<ITable> tables;

	public JsonDatabase(JSONObject jsonData) {
		this.jsonData = jsonData;
		// FIXME 2021/7/1  replace with: Factory
		// FIXME 2021/7/1  wait for me!!!     might cause error: data is always expired
		tables = ((List<Object>) jsonData.get("tables")).stream()
				.map(table -> ((JSONObject) table))
				.map(JsonTable::new).collect(toList());
	}

	@Override
	public ITable table(String tableName) {
		return tables.stream()
				.filter(table -> table.getName().equals(tableName))
				.findFirst().orElseThrow(() -> new RuntimeException("can't find table at: " + getName() + "." + tableName));
	}

	public void drop(String tableName) {
		tables.removeIf(table -> table.getName().equals(tableName));
	}

	@Override
	public List<ITable> getTables() {
		return tables;
	}

	@Override
	public ITable createTable(String tableName, List<FieldValues> fields) {
		throw new UnsupportedOperationException("JsonDatabase.createTable is not implemented yet.");
	}

	@Override
	public String getName() {
		return jsonData.getString("name");
	}

	@Override
	public void clear() {
		throw new UnsupportedOperationException("JsonDatabase.clear is not implemented yet.");
	}
}
